import React from 'react';
import {connect} from 'dva/index';
import {Cascader} from 'antd';

const R = require('ramda');


class StreetSelect extends React.Component {
    constructor(props) {
        super(props);
        this.state = {areaTree: []}
        this.initData(props.value);
    }

    componentWillReceiveProps(nextProps) {
        if (!R.equals(this.props.value)(nextProps.value)) {
            this.initData(nextProps.value)
        }
    }

    initData = (value) => {
        this._destroy = false; //假设数据异步返回后组件被销毁了，就不去调用setState方法，否则react会弹出警告
        this.props.dispatch({
            type: 'app/getAreaTree',
            onSuccess: (areaTree) => {
                if (!this._destroy) {
                    if (value && value.length > 2 && value[0] && value[1] && value[2]) { //初始值必须至少有省市区，且不为无效值
                        let provice = areaTree.filter(item => { return item.value === value[0] });
                        let city = provice[0].children.filter(item => { return item.value === value[1] });
                        let district = city[0].children.filter(item => { return item.value === value[2] });
                        this.props.dispatch({
                            type: "app/getAreaStreetsTree",
                            districtCode: district[0].value,
                            onSuccess: (streets) => {
                                if (!this._destroy) {
                                    district[0].children = streets;
                                    this.setState({ areaTree });
                                }
                            }
                        })
                    } else {
                        this.setState({ areaTree });
                    }
                }
            }
        });
    }


    componentWillUnmount() {
        this._destroy = true;
    }

    loadData = (selectedOptions) => {
        const targetOption = selectedOptions[selectedOptions.length - 1];
        targetOption.loading = true;
        this.props.dispatch({
            type: "app/getAreaStreetsTree",
            districtCode: selectedOptions[2].value,
            onSuccess: (data) => {
                targetOption.children = data
                targetOption.loading = false;
                this.setState({ areaTree: [...this.state.areaTree] });
            }
        })
    }

    render() {
        return (
            <Cascader
                loadData={this.loadData.bind(this)}
                options={this.state.areaTree}
                {...R.omit(['app', 'dispatch'])(this.props) }
                placeholder="请选择地区"
            />
        );
    }
}

export default connect(({ app }) => ({ app }))(StreetSelect)